package com.fhao.aop.proxy;

import org.springframework.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        //测试静态代理
//        HouseProxy proxy = new HouseProxy(new RealHouseSubject());
//        proxy.rentHouse();

        //测试JDK动态代理
        /**
         *     newProxyInstance(ClassLoader loader,Class<?>[] interfaces, InvocationHandler h)
         *     loader 加载我们的代理类的classload
         *     interfaces: 要实现的接口
         *     h 代理类要做的事情, 需要实现 InvacationHandler 这个接口
         */
        //目标对象
//        RealHouseSubject target = new RealHouseSubject();
//        //动态生成代理对象 (JDK只能代理接口)
//        //JDK代理接口运行成功
//        HouseSubject proxy = (HouseSubject) Proxy.newProxyInstance(target.getClass().getClassLoader(),
//                new Class[]{HouseSubject.class},new JDKInvocationHandler(target));
//        proxy.rentHouse();
//        proxy.saleHouse();

//        RealHouseSubject target = new RealHouseSubject();
//        //JDK代理类,运行失败
//        RealHouseSubject proxy = (RealHouseSubject) Proxy.newProxyInstance(target.getClass().getClassLoader(),
//                new Class[]{HouseSubject.class},new JDKInvocationHandler(target));
//        proxy.rentHouse();
//        proxy.saleHouse();

        //测试CGLib动态代理 (既能代理类又能代理接口)
        //代理接口,运行成功
//        HouseSubject target = new RealHouseSubject();
//        HouseSubject houseSubject = (HouseSubject) Enhancer.create(target.getClass(), new CGLibMethodInterceptor(target));
//        houseSubject.rentHouse();
//        houseSubject.saleHouse();

        //代理类,运行成功
        RealHouseSubject target = new RealHouseSubject();
        RealHouseSubject houseSubject = (RealHouseSubject) Enhancer.create(target.getClass(), new CGLibMethodInterceptor(target));
        houseSubject.rentHouse();
        houseSubject.saleHouse();
    }
}
